//
//  SettingViewController+TcpConnect.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-11.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "SettingViewController+TcpConnect.h"
#import "SettingViewController.h"
#import "MBProgressController.h"

@implementation SettingViewController (TcpConnect)



- (void)initNetworkCommunication
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    
//    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.119", PORT, &readStream, &writeStream);
    if([self.dataSeviceAddr.text isEqualToString:@""])
    {
        NSLog(@"数据服务地址为空");
        [[MBProgressController sharedInstance] showTipsOnlyText:@"数据服务地址为空"
                                                       AndDelay:1.5];
        return;
    }
    if([self.pushServerIP.text isEqualToString:@""])
    {
        NSLog(@"推送服务器IP为空");
        [[MBProgressController sharedInstance] showTipsOnlyText:@"推送服务器IP为空"
                                                       AndDelay:1.5];
        return;
    }
    if([self.pushSevicePORT.text isEqualToString:@""])
    {
        NSLog(@"推送服务端口为空");
        [[MBProgressController sharedInstance] showTipsOnlyText:@"推送服务端口为空"
                                                       AndDelay:1.5];
        return;
    }
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)self.pushServerIP.text, self.pushSevicePORT.text.integerValue, &readStream, &writeStream);
    self.inputStream = (__bridge_transfer NSInputStream *)readStream;
    self.outputStream = (__bridge_transfer NSOutputStream*)writeStream;
    [self.inputStream setDelegate:self];
    [self.outputStream setDelegate:self];
    [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream open];
    [self.outputStream open];
}


#pragma -mark
#pragma -mark NSStreamDelegate
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    NSString    *event;
    
    switch (eventCode) {
        case NSStreamEventNone:
            event = @"NSStreamEventNone";
            break;
        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            break;
        case NSStreamEventHasBytesAvailable:
        {
            event = @"NSStreamEventHasBytesAvailable";
            if(aStream == self.inputStream)
            {
                NSMutableData   *input = [[NSMutableData alloc] init];
                
                
                uint8_t buffer[1024];
                NSInteger len;
                while ([self.inputStream hasBytesAvailable]) {
                    len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
                    if(len > 0)
                    {
                        [input appendBytes:buffer length:len];
                    }
                }
                
                NSString    *resultstring = [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding];
                NSLog(@"接收:%@",resultstring);
                [[MBProgressController sharedInstance] showTipsOnlyText:resultstring
                                                               AndDelay:1.5];
            }
        }
            break;
        case NSStreamEventHasSpaceAvailable:
            event = @"NSStreamEventHasSpaceAvailable";
            if(aStream == self.outputStream)
            {
//                uint8_t buff[] = "Hello Server!";
//                //                uint8_t *buff = [_sendContent.text UTF8String];
//                [self.outputStream write:buff maxLength:strlen((const char*)buff)+1];
//                
//                [self.outputStream close];
                [[MBProgressController sharedInstance] showTipsOnlyText:@"测试TCP连接成功!"
                                                               AndDelay:1.5];
            }
            break;
        case NSStreamEventErrorOccurred:
            event = @"NSStreamEventErrorOccurred";
            [self close];//自定义的close
            break;
        case NSStreamEventEndEncountered:
            event = @"NSStreamEventEndEncountered";
            [[MBProgressController sharedInstance] showTipsOnlyText:@"与服务器连接中断..."
                                                           AndDelay:1.5];
            NSLog(@"Error:%ld:%@",(long)[[aStream streamError] code],[[aStream streamError] localizedDescription]);
            break;
        default:
            [self close];
            event = @"Unknown";
            break;
    }
    NSLog(@"event--%@",event);
}

-(void)close
{
    [self.outputStream close];
    [self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream setDelegate:nil];
    [self.inputStream close];
    [self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream setDelegate:nil];
}



@end
